// pages/shop/product_new.js
var app = getApp();
var currentProductId;
var dateTimePicker = require('../../datetime_picker.js');
Page({
  data:{
    uploadImg: null,
    categories: [],
    categoryIndex: 0,
    specs: [],
    specCount: 0,
    isSpec: false,
    act: 'create',
    photos: [],
    is_not_return: false,
    is_limit: false,
    isbuylimit: false,
    dateTimeArray: [],
    dateTime: [],
    dateTimeArray2: [],
    dateTime2: [],
    startYear: 2000,
    endYear: 2050
  },
  onLoad:function(options){
    if(options.id){
      currentProductId = options.id;
      this.setData({
        act: 'update'
      });
    }/* else {
      var that = this;
      app.util.appInfo(app, function (res) {
        if (res.result.shop_login_logo.length > 0) {
          var uploadImg = res.result.shop_login_logo;
          that.setData({
            uploadImg: uploadImg
          });
        }
      });
    }*/
    console.log(options)
     if(options.product_id){
         this.setData({
             buyLimit: true
         })
     }
 
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);
    this.setData({
        dateTime: obj.dateTime,
        dateTimeArray: obj.dateTimeArray,
        dateTime2: obj.dateTime,
        dateTimeArray2: obj.dateTimeArray,
    });
  },
  onReady: function(){
    console.log(this.data.act)
    var that = this;
    var shop = wx.getStorageSync('shop');
    app.func.req('product_cates/index', {
      shop_id: shop.id,
      is_business: true
    }, 'GET', function(res){
      var categories =  app.util.covertProductCates(res.result);
      for (var i = 0; i < categories.length; i++) {
        if (categories[i].is_platform == 1) {
          categories.splice(i,1);
          i--;
        }
      }
      
      that.setData({
        categories: categories
      });

      if (currentProductId > 0 && that.data.act == 'update') {
        app.func.req('products/show', {
          id: currentProductId,
          shop_id: shop.id
        }, 'GET', function(res){
          console.log(res);
          if (res.code == 'success') {
            var product =  res.result;
            console.log(product)
            var isSpec = false;
            if(product.spec.length > 0){
              isSpec = true;
            }
            that.setData({
              product: product,
              isSpec: isSpec,
              act: 'update',
              uploadImg: product.logo,
              specs: product.spec,
              specCount: product.spec.length,
              photos: product.photos,
              is_not_return: product.is_not_return == 1,
              is_limit: product.is_limit > 0
            });

            for(var i = 0; i < that.data.categories.length; i++){
              if (categories[i].id == product.product_cate_id) {
                that.setData({
                  categoryIndex: i
                });
                break;
              }
            }
          }
        },{
          token: wx.getStorageSync('token')
        });
      }
    });
  },
  save:function(e){
    var values = e.detail.value;
   var that =this;
    var name = e.detail.value.name.trim();
    var price = e.detail.value.price.trim();
    if(this.data.isbuyLimit)
        this.compareStartEndTime();
    if(name == ''){
      wx.showToast({
        title: '商品名不能为空',
        icon: 'error',
        duration: 2000,
        mask: true
      });
      return;
    }

    if (this.data.uploadImg == null) {
      wx.showToast({
        title: '请上传商品封面图',
        icon: 'error',
        duration: 2000,
        mask: true
      });
      return;
    }

    if(this.data.specCount == 0 &&
    (price == ''  || price == 0)){
      wx.showToast({
        title: '商品价格必须大于0',
        icon: 'error',
        duration: 2000,
        mask: true
      });
      return;
    }

    //组装规格数组
    var specs = [];
    for(var i = 0; i < this.data.specCount; i++){
      var specName = 'specs[' + i + '][name]';
      var specPrice = 'specs[' + i + '][price]';
      var specStock = 'specs[' + i + '][stock]';
      if(values[specName]!='' && values[specPrice]!='' && values[specStock]!='' && values[specPrice] > 0){
        specs.push({
          name: values[specName],
          price: values[specPrice],
          stock: values[specStock],
        });
      }
    }

    var params;
    if (this.data.act == 'update') {
      params = {
        name: e.detail.value.name.trim(),
        product_cate_id: this.data.categories[this.data.categoryIndex].id,
        specs: specs,
        content: e.detail.value.content,
        logo: this.data.uploadImg,
        price: e.detail.value.price,
        product_num: e.detail.value.product_num,
        id: currentProductId,
        photos: this.data.photos,
        is_not_return: this.data.is_not_return ? 1 : 0,
        is_limit: e.detail.value.is_limit
      };
    } else {
      params = {
        name: e.detail.value.name.trim(),
        product_cate_id: this.data.categories[this.data.categoryIndex].id,
        specs: specs,
        content: e.detail.value.content,
        logo: this.data.uploadImg,
        price: e.detail.value.price,
		product_num: e.detail.value.product_num,
        stock: 99,
        photos: this.data.photos,
        is_not_return: this.data.is_not_return ? 1 : 0,
        is_limit: e.detail.value.is_limit,
      };
      
    }
    if (that.data.isbuyLimit) {
        params.start_time = new Date(this.data.startTime).getTime();
        params.end_time = new Date(this.data.endTime).getTime();
        app.func.req('ms_products/' + this.data.act, params, 'POST', function (res) {
            console.log(params)
            console.log('更新结果：')
            console.log(res)

            if (res.code == 'success') {
                wx.showToast({
                    title: '添加成功！',
                    icon: 'success',
                    duration: 2000,
                    mask: true,
                    success: function () {
                        wx.switchTab({
                            url: './products'
                        })
                    }
                });
            } else if (res.msg == 'products.name.exist') {
                wx.showToast({
                    title: '商品名存在',
                    image: '/images/fail.png',
                    duration: 2000,
                    mask: true
                });
            } else if (res.msg == "products.name.blank") {
                wx.showToast({
                    title: '商品名不可以为空',
                    image: '/images/fail.png',
                    duration: 2000,
                    mask: true
                });
            } else if (res.msg == "products.num.limit") {
                wx.showToast({
                    title: '商品超过上限' + res.result + '个',
                    image: '/images/fail.png',
                    duration: 2000,
                    mask: true
                });
            } else {
                // wx.showToast({
                //   title: '添加失败',
                //   icon: 'error',
                //   duration: 2000,
                //   mask: true
                // });
            }
        }, {
                'token': wx.getStorageSync('token')
            });
    }
    else
    {
        app.func.req('products/' + this.data.act, params, 'POST', function(res){
        console.log(params)
        console.log('更新结果：')
        console.log(res)

        if (res.code == 'success') {
            wx.showToast({
            title: '添加成功！',
            icon: 'success',
            duration: 2000,
            mask: true,
            success: function(){
                wx.switchTab({
                url: './products'
                })
            }
            });
        } else if(res.msg == 'products.name.exist') {
            wx.showToast({
            title: '商品名存在',
            image: '/images/fail.png',
            duration: 2000,
            mask: true
            });
        } else if (res.msg == "products.name.blank"){
            wx.showToast({
            title: '商品名不可以为空',
            image: '/images/fail.png',
            duration: 2000,
            mask: true
            });
        } else if (res.msg == "products.num.limit") {
            wx.showToast({
            title: '商品超过上限'+res.result+'个',
            image: '/images/fail.png',
            duration: 2000,
            mask: true
            });
        } else {
            // wx.showToast({
            //   title: '添加失败',
            //   icon: 'error',
            //   duration: 2000,
            //   mask: true
            // });
        }
        },{
        'token': wx.getStorageSync('token')
        });
    }
  },
  chooseImage: function () {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var tempFilePaths = res.tempFilePaths;
        wx.showLoading({title: '准备上传...', mask: true});
        app.func.upload('file/upload', tempFilePaths[0], {}, function(res){
          var res =  JSON.parse(res);
          if(res.code == 'success'){
            that.setData({
              uploadImg: res.result[0]
            });

            wx.showToast({
              title: '上传成功',
              icon: 'success',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '上传失败',
              image: '/images/fail.png',
              duration: 2000
            })
          }
        },{
          token: wx.getStorageSync('token')
        });
      }
    });
  },
  bindCategoryChange: function(e) {
    this.setData({
      categoryIndex: e.detail.value
    })
  },
  addSpec: function(){
    var specs = this.data.specs;
    if(specs.length>0){
      if(specs[specs.length-1].name == ''||specs[specs.length-1].price==''){
        wx.showToast({
          title: '规格不可以为空',
          image: '/images/fail.png',
          duration: 3000
        })
      }else{
        specs.push({
          name: '',
          price: ''
        });
        this.setData({
          specs: specs,
          specCount: this.data.specCount + 1
        });
      }
    }else{
      specs.push({
        name: '',
        price: ''
      });
      this.setData({
        specs: specs,
        specCount: this.data.specCount + 1
      });
    }
  },
  changeSpecStock: function(e){
    var stock = e.detail.value;
    var index = e.target.dataset.index;
    var specs = this.data.specs;
    specs[index].stock = stock;
    this.setData({
      specs: specs
    })
  },
  changeSpecName: function(e){
    var name = e.detail.value;
    var index = e.target.dataset.index;
    var specs = this.data.specs;
    specs[index].name = name;
    this.setData({
      specs: specs
    })
  },
  changeSpecPrice: function (e) {
    var price = e.detail.value;
    var index = e.target.dataset.index;
    var specs = this.data.specs;
    specs[index].price = price;
    this.setData({
      specs: specs
    })
  },
  doSpec: function(e){
    this.setData({
      isSpec: e.detail.value
    });
  },
  delSpec: function(e){
    var index = e.target.dataset.index;
    var specs = this.data.specs;
    specs.splice(index,1);
    this.setData({
      specs: specs,
      specCount: this.data.specCount - 1
    })
  },
  productImagesUpload: function (e) {
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        console.log(res)
        var tempFilePaths = res.tempFilePaths;
        var success = 0;
       // wx.showLoading({ title: '图片上传中...', mask: true });
        for(var i = 0; i < tempFilePaths.length; i++){
          app.func.upload('file/upload', tempFilePaths[i], {}, function (res) {
              var res =  JSON.parse(res);
              that.setData({
                photos: that.data.photos.concat(res.result[0])
              });
              success ++;
              if (success == tempFilePaths.length) {
                console.log(tempFilePaths.length);
                wx.hideLoading();
                wx.showToast({
                  title: '上传完成',
                  icon: 'success',
                  duration: 2000
                })
              }
          }, {
            token: wx.getStorageSync('token')
          });
        }
      },
      fail: function(res){
        console.log(res)
      }

    })
  },
  delImg: function(e){
    var that = this;
    var photos = that.data.photos;
    var index = e.target.dataset.index;
    wx.showActionSheet({
      itemList: ['前移','后移','删除'],
      success: function (res) {
        if(res.tapIndex == 0 && index > 0){
          var c_photo = photos.splice(index-1, 1);
          photos.splice(index, 0, c_photo[0]);
        } else if (res.tapIndex == 1 && index + 1 < photos.length) {
          var c_photo = photos.splice(index + 1, 1);
          photos.splice(index, 0, c_photo[0]);
        } else if (res.tapIndex == 2) {
          photos.splice(index, 1);

        }
        that.setData({
          photos: photos
        })
      }
    })
  },
  returnSwitch: function(e){
    this.setData({
      is_not_return: e.detail.value
    });
  },
  limitSwitch: function (e) {
    this.setData({
      is_limit: e.detail.value
    });
  },
  changeDateTime(e) {
      var startTime = '';
      for (var i = 0; i < 6; i++) {
          var arr = this.data.dateTimeArray[i][this.data.dateTime[i]];
          if (i < 2)
              startTime += arr + "-";
          else if (i > 2 && i < 5)
              startTime += arr + ":";
          else
              startTime += arr + " "
      }
      console.log(startTime)
      this.setData({ 
          dateTime: e.detail.value ,
           startTime: startTime
        });
        console.log(e.detail.value)
      //this.compareStartEndTime();
  },
  changeDateTimeColumn(e) {
      var arr = this.data.dateTime, dateArr = this.data.dateTimeArray;
      arr[e.detail.column] = e.detail.value;
      dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
      this.setData({
          dateTimeArray: dateArr,
          dateTime: arr
      });
  },
  changeDateTime2(e) {
      var endTime = '';
      for (var i = 0; i < 6; i++) {
          var arr = this.data.dateTimeArray2[i][this.data.dateTime2[i]]
          if (i < 2)
              endTime += arr + "-";
          else if (i > 2 && i < 5)
              endTime += arr + ":";
          else
              endTime += arr + " "
      }
      console.log(endTime)
      this.setData({ 
          dateTime2: e.detail.value,
          endTime : endTime
        });
      //this.compareStartEndTime();
  },
  compareStartEndTime(){
      var endtime = new Date(this.data.endTime).getTime() || new Date().getTime() ;
      var starttime = new Date(this.data.startTime).getTime() || new Date().getTime();
        if( endtime<starttime ){
            wx.showToast({
                title: '结束时间必须大于开始时间',
                icon: 'none',
                duration: 2000  
            })
        }
  },
  changeDateTimeColumn2(e) {
      var arr = this.data.dateTime2, dateArr = this.data.dateTimeArray2;
      arr[e.detail.column] = e.detail.value;
      dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);
      this.setData({
          dateTimeArray2: dateArr,
          dateTime2: arr
      });
  },
  buyLimited(e){
      var isbuyLimit ;
      e.detail.value? isbuyLimit=true: isbuyLimit=false;
      this.setData({
          isbuylimit: isbuyLimit
      })
  }
})
